package com.jvm.binary.initialize.invokedynamic;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * Demo01.. jvm invokedynamic 通过代码层面控制invokevirtual
 *
 * @author Lizhong
 * @date 2019/3/15
 */
public class MethodHandlesDemo01 {
    static class A {
        public void println(String s) {
            System.out.println(A.class.getName() + ":i");
        }
    }

    public static void main(String[] args) throws Throwable {
        int i = 0;
        while (i < 5) {
            boolean b = i % 2 == 0;

            Object obj = b ? System.out : new A();
            choice(obj).invokeExact("hello");
            i++;
        }

    }

    private static MethodHandle choice(Object obj) throws Exception {
        MethodType methodType = MethodType.methodType(void.class, String.class);
        return MethodHandles.lookup().findVirtual(obj.getClass(), "println", methodType).bindTo(obj);
    }
}
